package com.dq.demos.web.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class ZlbpInterfaceTool {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";

    private static final String ALGORITHM = "AES";

    /**
     * 参数加密
     * @param encryptKey
     * @param content
     * @return
     */
    public static String encrypt(String encryptKey, String content) {
        try {
            Field field = Class.forName("javax.crypto.JceSecurity").getDeclaredField("isRestricted");
            field.setAccessible(true);

            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

            field.set(null, false);
            SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey.getBytes(), ALGORITHM);
            Cipher ecipher = Cipher.getInstance(TRANSFORMATION);
            ecipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            return Base64Utils.encodeToString(ecipher.doFinal(content.getBytes(DEFAULT_CHARSET)));
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }


    public static String getSignature(String data, String key) {
        Mac mac;
        try {
            mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKey);
            mac.update(data.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            System.out.println("获取Signature签名信息异常：" + e);
            return null;
        }
        return byte2Hex(mac.doFinal());
    }

    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuffer = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}
